package com.chilly.db1.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * Created by Chilly Cui on 2020/11/17.
 */
@Service
public class HumanTransactionalService {

    @Autowired
    private TransactionTemplate transactionTemplate;

    //使用TransactionTemplate 进行编程式事务管理的示例代码如下：
    public void test(){
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                try {

                    // ....  业务代码
                } catch (Exception e){
                    //回滚
                    transactionStatus.setRollbackOnly();
                }
            }
        });
    }

    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    //使用 TransactionManager 进行编程式事务管理的示例代码如下：
    public void test2(){
        TransactionStatus status = platformTransactionManager.getTransaction(new DefaultTransactionDefinition());
        try {

            // ....  业务代码
        } catch (Exception e){
            //回滚
            status.setRollbackOnly();
        }

    }

}
